<?php

/**
 * 加载语言包
 */
service('i18n')->import('country');

class OaCountries extends \Formax\Model
{

    /**
     *
     * @var integer
     */
    public $country_id;

    /**
     *
     * @var string
     */
    public $country = '';

    /**
     *
     * @var string
     */
    public $abbr = '';

    /**
     *
     * @var integer
     */
    public $area_code = 0;

    /**
     *
     * @var integer
     */
    public $time_diff = 0;

    /**
     *
     * @var integer
     */
    public $enabled = 1;

    /**
     *
     * @var integer
     */
    public $copymaster_id = 0;

    public function beforeValidation()
    {
        parent::beforeValidation();

        if (! trim($this->country)) {
            return $this->errorMessage('Country name is required');
        }

        if ($find = self::findFirst("country='{$this->country}'")) {
            if ($find->country_id != $this->country_id) {
                return $this->errorMessage('Country name already exists');
            }
        }
    }

    public static function findFirstByCountryId($country_id)
    {
        static $cached = null;

        if (! $country_id) return false;

        if ($cached === null) {
            foreach (self::find() as $row) {
                $cached[$row->country_id] = $row->toArray();
            }
        }

        return array_get($cached, $country_id, false);
    }

    public static function getName($country_id, $lang = null)
    {
        $country = self::findFirstByCountryId($country_id);

        return $country ? __($country['country'], null, $lang) : null;
    }

}
